package com.chookss.home.audit;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.home.audit.adapter.ClockInAuditAdapter;
import com.chookss.home.audit.adapter.ReimbursementAuditAdapter;
import com.chookss.home.audit.seal.SealAuditAdapter;
import com.chookss.home.entity.WorkNewEntity;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.XJson;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.OkGoUtil;
import com.chookss.tools.okgoconfig.callback.JsonCallback;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.google.gson.reflect.TypeToken;
import com.lvgroup.hospital.base.BaseAct;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.Nullable;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;

public class AuditActivity extends BaseAct {
//待审批列表 从待审批右上角进入，一般只有管理者才有数据

    @BindView(R.id.tvBottomInit)
    TextView tvBottomInit;
    @BindView(R.id.common_title_txt)
    TextView common_title_txt;
    @BindView(R.id.ivChoice)
    ImageView ivChoice;
    @BindView(R.id.tvBottomSure)
    TextView tvBottomSure;
    @BindView(R.id.rvView)
    RecyclerView recyclerView;
    @BindView(R.id.srlView)
    SmartRefreshLayout smrRf;
    @BindView(R.id.llBottom)
    LinearLayout llBottom;
    private BaseQuickAdapter adapter;
    private List<WorkNewEntity> list = new ArrayList<>();
    private int currentPage = 1;
    private int pageSize = 20;
    private boolean isEnd = false;//是否到底
    private View emptyView;
    private TextView tvNone;//空布局;
    private boolean isAllSelect = false;
    private int num = 0;//选中的审批对象
    private int type = 3;// 1新闻2视频3补卡4-请假5-外勤6图文7报销8物料9借款10补贴11用章12维修13交付14离职15晋升16回款17修改项目金额18入职19加班

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_clock_manager_examine);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        type = getIntent().getIntExtra("type", 3);
        if (4 == type) {
            common_title_txt.setText("请假待审批");
        } else if (7 == type) {
            common_title_txt.setText("报销待审批");
        } else if (8 == type) {
            common_title_txt.setText("物品待审批");
        } else if (9 == type) {
            common_title_txt.setText("借款待审批");
        }  else if (10 == type) {
            common_title_txt.setText("补贴待审批");
        } else if (11 == type) {
            common_title_txt.setText("用章待审批");
        }else if (14 == type) {
            common_title_txt.setText("入/离职待审批");
        }else if (15 == type) {
            common_title_txt.setText("晋升待审批");
        }else if (16 == type||17 == type) {
            common_title_txt.setText("项目管理待审批");
        }else if (18 == type) {
            common_title_txt.setText("入职待审批");
        }else if (19 == type) {
            common_title_txt.setText("加班待审批");
        } else {
            common_title_txt.setText("考勤待审批");
        }
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) smrRf.getLayoutParams();
        params.setMargins(0, Utils.dip2px(this, 12), 0, 0);
        smrRf.setLayoutParams(params);
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        if (type == 3 || type == 4||type == 14 || type == 15) {
            adapter = new ClockInAuditAdapter(R.layout.item_clock_manager_examine, this, list);
        } else if (type == 7 || type == 8 || type == 9|| type == 10|| type == 12|| type == 13|| type == 16|| type == 17) {
            adapter = new ReimbursementAuditAdapter(R.layout.item_reimbursement_audit, this, list);
        } else if (type ==11) {
            adapter = new SealAuditAdapter(R.layout.item_seal_audit, this, list);
        }
        ((SimpleItemAnimator) recyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        recyclerView.setAdapter(adapter);
        emptyView = LayoutInflater.from(this).inflate(R.layout.layout_common_empty, recyclerView, false);
        tvNone = emptyView.findViewById(R.id.tvEmpty);
        tvNone.setText("暂无审批记录");
        smrRf.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isEnd) {//has next page
                    MyToast.show("没有更多数据了");
                    loadEnd();
                } else {
                    currentPage++;
                    getData();
                }
            }
        });
        smrRf.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                isEnd = false;
                currentPage = 1;
                getData();
            }
        });
        smrRf.autoRefresh();
    }

    private void getData() {
        Map<String, String> map = new HashMap<>();
        //待审核 传0 已审核不传
        map.put("auditStatus", "0");
        map.put("pageNum", currentPage + "");
        map.put("pageSize", pageSize + "");
        // 1-新闻 2-视频 3-补卡 4-请假 5-外勤 6-图文7报销8物料9借款10补贴11用章
        if (type == 3) {
            //考勤系列
            map.put("type", "3,5");
        }else if (type == 8) {
            //物品系列
            map.put("type", "8,12");
        }else if (type == 16||type == 17) {
            //项目管理
            map.put("type", "13,16,17");
        }else if (type == 14) {
            //离职晋升
            map.put("type", "14,18");
        } else {
            map.put("type", type + "");
        }
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<WorkNewEntity>>>() {
        }.getType(), null, Urls.selectKqMyWorkList, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<WorkNewEntity>>() {
            @Override
            public void onSuccess(List<WorkNewEntity> data) {
                if (currentPage == 1) {
                    list.clear();
                    adapter.notifyDataSetChanged();
                    num = 0;
                    isAllSelect = false;
                    ivChoice.setBackgroundResource(R.drawable.shape_circle_b5b5b5_20);
                    tvBottomInit.setText("已选中" + num + "个");
                }
                if (smrRf == null) {
                    return;
                }
                if (data != null && data.size() > 0) {
                    if (data.size() < pageSize) {
                        isEnd = true;
                    }
                    int old = list.size();
                    list.addAll(data);
                    adapter.notifyItemRangeChanged(old, data.size());
                    llBottom.setVisibility(View.VISIBLE);
                } else {
                    isEnd = true;
                    if (list.size() == 0) {
                        llBottom.setVisibility(View.GONE);
                        adapter.setEmptyView(emptyView);
                    } else {
                        llBottom.setVisibility(View.VISIBLE);
                    }
                }
                loadEnd();
            }

            @Override
            public void onError(String errorMsg) {
                loadEnd();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void refreshData() {
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setSelect(isAllSelect);
        }
        adapter.notifyDataSetChanged();
        if (isAllSelect) {
            num = list.size();
        } else {
            num = 0;
        }
        tvBottomInit.setText("已选中" + num + "个");
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getMap() != null) {
            Map<String, String> map = messageEvent.getMap();
            if (map.containsKey("ClockInAudit_position")) {
                int position = Utils.changeNumber(map.get("ClockInAudit_position"));
                if (position < 0) {
                    return;
                }
                if (position >= list.size()) {
                    return;
                }
                if (list.get(position).isSelect()) {
                    list.get(position).setSelect(false);
                    num--;
                } else {
                    list.get(position).setSelect(true);
                    num++;
                }
                tvBottomInit.setText("已选中" + num + "个");
                adapter.notifyItemChanged(position);
                if (num == list.size()) {
                    isAllSelect = true;
                    ivChoice.setBackgroundResource(R.drawable.icon_fx_select);
                } else {
                    isAllSelect = false;
                    ivChoice.setBackgroundResource(R.drawable.shape_circle_b5b5b5_20);
                }
            }
        } else {
            String msg = messageEvent.getMessage();
            if (Utils.isNull(msg)) {
                return;
            }
            if (msg.equals("RefreshClockInManagerExamine")||msg.equals("RefreshGroupRecord") || msg.equals("RefreshClockInHolidayRecord") || msg.equals("RefreshReimbursementRecord")||msg.equals("RefreshSealRecord") || msg.equals("RefreshShopRecord")) {
                smrRf.autoRefresh();
            }
        }
    }

    private void passData() {
        Map<String, Object> map = new HashMap<>();
        List<Map<String, String>> lists = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).isSelect()) {
                //1审核通过 2审核未通过0未审核
                Map<String, String> news = new HashMap<>();
                news.put("projectCode", list.get(i).getProjectCode());
                news.put("id", list.get(i).getId());
                news.put("employeeCode", list.get(i).getCreateEmployeeCode());
                // 1-新闻 2-视频 3-补卡 4-请假 5-外勤 6-图文7报销
                news.put("type", list.get(i).getWorkFlowType());
                news.put("auditStatus", "1");
                if ("3".equals(list.get(i).getWorkFlowType())) {
                    if (!Utils.isNull(list.get(i).getParams().getStartTime())) {
                        news.put("shangbanCd", "1");//1上班0下班
                    } else {
                        news.put("shangbanCd", "0");//1上班0下班
                    }
                }
                lists.add(news);
            }
        }
        map.put("tbKmerWorkFlowProjects", XJson.listToJsArrays(lists));
        showLoading();
        MyHttpRequest.postRequestJson(Urls.auditWorkfolwProject, this, XJson.mapToJObj(map).toString(), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                dismissLoading();
                try {
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        MyToast.show("提交成功");
                        EventBus.getDefault().post(new MyEvent("RefreshAudit"));
                        smrRf.autoRefresh();
                    } else {
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"), jsonObject.getString("msg"));
                        } else {
                            MyToast.show(jsonObject.getString("msg"));
                        }
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    dismissLoading();
                    MyToast.show("操作失败，请稍后重试");
                }
            }
        });
    }

    private void loadEnd() {
        if (null != smrRf && smrRf.getState() == RefreshState.Refreshing)
            smrRf.finishRefresh(true);
        if (null != smrRf && smrRf.getState() == RefreshState.Loading)
            smrRf.finishLoadMore(true);
    }

    @OnClick({R.id.common_title_back, R.id.ll_record, R.id.llChoice, R.id.tvBottomSure})
    public void onClick(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.common_title_back:
                finish();
                break;
            case R.id.ll_record:
                intent = new Intent(this, AuditOverActivity.class);
                intent.putExtra("type", type);
                startActivity(intent);
                break;
            case R.id.tvBottomSure:
                if (Urls.antiShake.check()) {
                    return;
                }
                if (num > 0) {
                    passData();
                } else {
                    MyToast.show("至少选择一项");
                }
                break;
            case R.id.llChoice:
                //全选
                if (isAllSelect) {
                    isAllSelect = false;
                    ivChoice.setBackgroundResource(R.drawable.shape_circle_b5b5b5_20);
                } else {
                    isAllSelect = true;
                    ivChoice.setBackgroundResource(R.drawable.icon_fx_select);
                }
                refreshData();
                break;
        }
    }
}
